package cn.ybk.basic.interceptor;

import cn.ybk.basic.annotation.PreAuthorize;
import cn.ybk.basic.jwt.JwtUtils;
import cn.ybk.basic.jwt.Payload;
import cn.ybk.basic.jwt.RsaUtils;
import cn.ybk.basic.jwt.UserInfo;
import cn.ybk.basic.util.ThreadLocalUtil;
import cn.ybk.system.domain.Permission;
import cn.ybk.system.mapper.PermissionMapper;
import cn.ybk.user.domain.Logininfo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;
import java.util.concurrent.TimeUnit;

@Component // 需要加上此注解将当前登录拦截器交给spring管理
public class LoginInterceptor implements HandlerInterceptor {

    @Value("${jwt.pub}")
    private String jwtPubKey;

    /**
     * jwt
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 3.1.设置编码字符集
        response.setCharacterEncoding("UTF-8");
        // 3.2.设置响应参数类型为JSON
        response.setContentType("application/json;charset=UTF-8");
        // 1.从header中获取token
        String token = request.getHeader("token");
        if (StringUtils.isNotBlank(token)){
            // 获取公钥
            PublicKey publicKey = RsaUtils.getPublicKey(JwtUtils.class.getClassLoader().getResource(jwtPubKey).getFile());
            // 通过token获取载荷
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            if (null != payload && payload.getUserInfo() != null){
                UserInfo userInfo = payload.getUserInfo();
                // 将用户信息放入到 threadLocal中
                ThreadLocalUtil.set(userInfo);
                // 只有后台才有权限
                if (0 == userInfo.getLogininfo().getType()){
                    // 根据logininfoId获取权限sn集合
                    //获取当前请求的方法
                    HandlerMethod methodHandle = (HandlerMethod) handler;
                    PreAuthorize pre = methodHandle.getMethodAnnotation(PreAuthorize.class);
                    if (null != pre){
                        String sn = pre.sn();
                        if (!userInfo.getPermissions().contains(sn)){
                            // 提示它没有权限
                            // 3.3.获取到打印流,并设置响应数据
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"resultObj\":\"noPermission\"}");
                            // 3.4.刷新、关流
                            writer.flush();
                            writer.close();
                            return false;
                        }
                    }
                }
                // 放行
                return true;
            }
        }
        // 3.3.获取到打印流,并设置响应数据
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"resultObj\":\"noLogin\"}");
        // 3.4.刷新、关流
        writer.flush();
        writer.close();
        // 返回false 是拦截请求
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 渲染之前 将ThreadLocal删除
        ThreadLocalUtil.remove();
    }
}